//
//  LoginMainView.m
//  ProjectForCustomer
//
//  Created by 钟游 on 2019/8/25.
//  Copyright © 2019年 钟游. All rights reserved.
//

#import "LoginMainView.h"
#import "LoginViewModel.h"
#import "ThirdLoginShareView.h"
#import <UMShare/UMShare.h>

@interface LoginMainView()<ThirdLoginShareViewDelegate,UITextViewDelegate>{
    NSInteger count;
}
@property(nonatomic,strong)UIImageView * bgView;
@property(nonatomic,strong)UIImageView * logoImageView;
@property(nonatomic,strong)UIImageView * titleImageView;
@property(nonatomic,strong)UITextField * phoneNumberTF;
@property(nonatomic,strong)UITextField * checkTF;
@property(nonatomic,strong)CustomLabel * delegateLabel;
@property(nonatomic,strong)CustomLabel * intructionLabel;
@property(nonatomic,strong)CustomButton * selectBtn;
@property(nonatomic,strong)CustomButton * loginBtn;
@property(nonatomic,strong)ThirdLoginShareView * thirdView;
@property(nonatomic,strong)LoginViewModel * viewModel;
@property (strong, nonatomic)  UITextView * titleTextView;

@property(nonatomic,strong)NSTimer * timer;
@end
@implementation LoginMainView
-(instancetype)initWithViewModel:(id<ViewModelProtocol>)viewModel{
    self.viewModel =(LoginViewModel*)viewModel;
    return  [super initWithViewModel:viewModel];
}
-(void)zy_bindViewModel{
        @weakify(self);
    [[self.viewModel.senderCodeSubject takeUntil:self.rac_willDeallocSignal] subscribeNext:^(id  _Nullable x) {
        @strongify(self);
        self->count = 60;
        self.timer = [NSTimer timerWithTimeInterval:1 target:self selector:@selector(timerAction) userInfo:nil repeats:YES];
        [[NSRunLoop mainRunLoop] addTimer:self.timer forMode:NSDefaultRunLoopMode];

    }];
    [[self.viewModel.weiSubject takeUntil:self.rac_willDeallocSignal]subscribeNext:^(id  _Nullable x) {
        [self.viewModel.delegateCommand execute:nil];
    }];
  
    
}

#pragma mark -- 定时器
-(void)timerAction{
    CustomButton * btn =[self viewWithTag:100];
    if (count==0) {
        [self.timer invalidate];
        self.timer = nil;
        btn.userInteractionEnabled = YES;
        [btn setTitle:@"获取验证码" forState:UIControlStateNormal];
    }else{
        [btn setTitle:[NSString stringWithFormat:@"剩余时间(%ld)秒",count] forState:UIControlStateNormal];
        count--;
    }
 
}
-(void)zy_setupViews{
    [self addSubview:self.bgView];
    [self addSubview:self.logoImageView];
    [self addSubview:self.titleImageView];
    [self addSubview:self.phoneNumberTF];
    [self addSubview:self.checkTF];
    [self addSubview:self.selectBtn];
    [self addSubview:self.titleTextView];
    [self addSubview:self.loginBtn];
    [self addSubview:self.thirdView];
}
/**
 验证码手机号
 
 @param mobileNum 手机号
 @return YES 通过 NO 不通过
 */
- (BOOL)validateContactNumber:(NSString *)mobileNum
{
    /**
     * 手机号码:
     * 13[0-9], 14[5,7], 15[0, 1, 2, 3, 5, 6, 7, 8, 9], 16[6], 17[5, 6, 7, 8], 18[0-9], 170[0-9], 19[89]
     * 移动号段: 134,135,136,137,138,139,150,151,152,157,158,159,182,183,184,187,188,147,178,1705,198
     * 联通号段: 130,131,132,155,156,185,186,145,175,176,1709,166
     * 电信号段: 133,153,180,181,189,177,1700,199
     */
    NSString *MOBILE = @"^1(3[0-9]|4[57]|5[0-35-9]|6[6]|7[05-8]|8[0-9]|9[89])\\d{8}$";
    
    NSString *CM = @"(^1(3[4-9]|4[7]|5[0-27-9]|7[8]|8[2-478]|9[8])\\d{8}$)|(^1705\\d{7}$)";
    
    NSString *CU = @"(^1(3[0-2]|4[5]|5[56]|66|7[56]|8[56])\\d{8}$)|(^1709\\d{7}$)";
    
    NSString *CT = @"(^1(33|53|77|8[019]|99)\\d{8}$)|(^1700\\d{7}$)";
    
    /**
     * 大陆地区固话及小灵通
     * 区号：010,020,021,022,023,024,025,027,028,029
     * 号码：七位或八位
     */
    // NSString * PHS = @"^0(10|2[0-5789]|\\d{3})\\d{7,8}$";
    
    NSPredicate *regextestmobile = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", MOBILE];
    NSPredicate *regextestcm = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CM];
    NSPredicate *regextestcu = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CU];
    NSPredicate *regextestct = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CT];
    // NSPredicate *regextestPHS = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", PHS];
    
    if(([regextestmobile evaluateWithObject:mobileNum] == YES)
       || ([regextestcm evaluateWithObject:mobileNum] == YES)
       || ([regextestct evaluateWithObject:mobileNum] == YES)
       || ([regextestcu evaluateWithObject:mobileNum] == YES)) {
        return YES;
    } else {
        return NO;
    }
}
#pragma mark -- 获取验证码
-(void)getCheckCode:(CustomButton*)btn{
    if ([self validateContactNumber:self.phoneNumberTF.text]) {
        btn.userInteractionEnabled = NO;
        [self.viewModel.senderCodeCommand execute:self.phoneNumberTF.text];
    }else{
        [self makeToast:@"请输入正确手机号" duration:2.0f position:CSToastPositionCenter];
    }
}
#pragma mark -- 登录
-(void)loginClick{
    if (self.checkTF.text.length==6) {
        NSDictionary * dict =@{@"phone":self.phoneNumberTF.text,
                               @"verificationCode":self.checkTF.text
                               };
        [self.viewModel.loginCommand execute:dict];
    }else{
        [self makeToast:@"请输入验证码" duration:2.0f position:CSToastPositionCenter];
    }
}
#pragma mark -- sharedelegate
-(void)clickBtnWithTitle:(NSString *)title{
    if ([title isEqualToString:@"qq"]) {
        [self getAuthWithUserInfoFromQQ];
    }else if ([title isEqualToString:@"微博"]){
        [self getAuthWithUserInfoFromSina];
    }else{
        [self getAuthWithUserInfoFromWechat];
    }
}
#pragma mark --qq
- (void)getAuthWithUserInfoFromQQ
{
    [[UMSocialManager defaultManager] getUserInfoWithPlatform:UMSocialPlatformType_QQ currentViewController:nil completion:^(id result, NSError *error) {
        if (error) {
            
        } else {
            UMSocialUserInfoResponse *resp = result;
            
            // 授权信息
            NSLog(@"QQ uid: %@", resp.uid);
            NSLog(@"QQ openid: %@", resp.openid);
            NSLog(@"QQ unionid: %@", resp.unionId);
            NSLog(@"QQ accessToken: %@", resp.accessToken);
            NSLog(@"QQ expiration: %@", resp.expiration);
            
            // 用户信息
            NSLog(@"QQ name: %@", resp.name);
            NSLog(@"QQ iconurl: %@", resp.iconurl);
            NSLog(@"QQ gender: %@", resp.unionGender);
            
            // 第三方平台SDK源数据
            NSLog(@"QQ originalResponse: %@", resp.originalResponse);
            NSDictionary * info =@{@"unionId":resp.uid,
                                   @"loginType":@"3",
                                   @"accessToken":resp.accessToken
                                   };
            [self.viewModel.thirdLoginCommand execute:info];
        }
    }];
}
#pragma mark -- weixin
- (void)getAuthWithUserInfoFromWechat
{
    [[UMSocialManager defaultManager] getUserInfoWithPlatform:UMSocialPlatformType_WechatSession currentViewController:nil completion:^(id result, NSError *error) {
        if (error) {
            
        } else {
            UMSocialUserInfoResponse *resp = result;
            
            // 授权信息
            NSLog(@"Wechat uid: %@", resp.uid);
            NSLog(@"Wechat openid: %@", resp.openid);
            NSLog(@"Wechat unionid: %@", resp.unionId);
            NSLog(@"Wechat accessToken: %@", resp.accessToken);
            NSLog(@"Wechat refreshToken: %@", resp.refreshToken);
            NSLog(@"Wechat expiration: %@", resp.expiration);
            
            // 用户信息
            NSLog(@"Wechat name: %@", resp.name);
            NSLog(@"Wechat iconurl: %@", resp.iconurl);
            NSLog(@"Wechat gender: %@", resp.unionGender);
            
            // 第三方平台SDK源数据
            NSLog(@"Wechat originalResponse: %@", resp.originalResponse);
            NSDictionary * info =@{@"unionId":resp.uid,
                                   @"loginType":@"1",
                                   @"accessToken":resp.accessToken
                                   };
            [self.viewModel.thirdLoginCommand execute:info];
        }
    }];
}
#pragma mark -- xinlan
- (void)getAuthWithUserInfoFromSina
{
    [[UMSocialManager defaultManager] getUserInfoWithPlatform:UMSocialPlatformType_Sina currentViewController:nil completion:^(id result, NSError *error) {
        if (error) {
            
        } else {
            UMSocialUserInfoResponse *resp = result;
            
            // 授权信息
            NSLog(@"Sina uid: %@", resp.uid);
            NSLog(@"Sina accessToken: %@", resp.accessToken);
            NSLog(@"Sina refreshToken: %@", resp.refreshToken);
            NSLog(@"Sina expiration: %@", resp.expiration);
            
            // 用户信息
            NSLog(@"Sina name: %@", resp.name);
            NSLog(@"Sina iconurl: %@", resp.iconurl);
            NSLog(@"Sina gender: %@", resp.unionGender);
            
            // 第三方平台SDK源数据
            NSLog(@"Sina originalResponse: %@", resp.originalResponse);
            NSDictionary * info =@{@"unionId":resp.uid,
                                   @"loginType":@"2",
                                   @"accessToken":resp.accessToken
                                   };
            [self.viewModel.thirdLoginCommand execute:info];
        }
    }];
}
#pragma mark -- lazy
-(LoginViewModel *)viewModel{
    if (!_viewModel) {
        _viewModel=[[LoginViewModel alloc]init];
    }
    return _viewModel;
}
-(UIImageView *)bgView{
    if (!_bgView) {
        _bgView=[[UIImageView alloc]initWithFrame:CGRectMake(0, 0, KscreenWidth, KscreenHeight)];
        _bgView.image=[UIImage imageNamed:@"bg_login"];
    }
    return _bgView;
}
-(UIImageView *)logoImageView{
    if (!_logoImageView) {
        _logoImageView=[[UIImageView alloc]initWithFrame:CGRectMake(KscreenWidth/2-34, 49+HEIGHT_STATUSBAR, 68, 68)];
        _logoImageView.image=[UIImage imageNamed:@"现在电影 标"];
    }
    return _logoImageView;
}
-(UIImageView *)titleImageView{
    if (!_titleImageView) {
        _titleImageView=[[UIImageView alloc]initWithFrame:CGRectMake(KscreenWidth/2-27.5, CGRectGetMaxY(self.logoImageView.frame)+13, 55, 12.5)];
        _titleImageView.image = [UIImage imageNamed:@"现在电影图标"];
    }
    return _titleImageView;
}
-(UITextField *)phoneNumberTF{
    if (!_phoneNumberTF) {
        _phoneNumberTF=[[UITextField alloc]initWithFrame:CGRectMake(52.5, CGRectGetMaxY(self.titleImageView.frame)+30, KscreenWidth-101, 43)];
        _phoneNumberTF.borderStyle= UITextBorderStyleNone;
        _phoneNumberTF.layer.cornerRadius = 20;
        _phoneNumberTF.layer.borderWidth = .5;
        _phoneNumberTF.layer.backgroundColor = UIColorFromRGB(0xCFCFCF).CGColor;
        _phoneNumberTF.layer.masksToBounds = YES;
       _phoneNumberTF.backgroundColor=[UIColorFromRGB(0xFFFFFF)colorWithAlphaComponent:.21];
        _phoneNumberTF.attributedPlaceholder = [[NSAttributedString alloc]initWithString:@"请输入手机号码" attributes:@{NSFontAttributeName:[UIFont boldSystemFontOfSize:12], NSForegroundColorAttributeName:UIColorFromRGB(0xFFFFFF)}];
        _phoneNumberTF.textColor=UIColorFromRGB(0xFFFFFF);
        _phoneNumberTF.textAlignment = NSTextAlignmentCenter;
        _phoneNumberTF.font=[UIFont systemFontOfSize:12];
        _phoneNumberTF.keyboardType=UIKeyboardTypeDecimalPad;
        UIView * leftView=[[UIView alloc]initWithFrame:CGRectMake(0, 0, 97, 43)];
        _phoneNumberTF.leftView = leftView;
        CustomLabel * lab =[[CustomLabel alloc]initWithFrame:CGRectMake(0, 0, 91, 43) andText:@"中国大陆" andFont:13 andColor:UIColorFromRGB(0xFFFFFF)];
        lab.textAlignment = NSTextAlignmentCenter;
        [leftView addSubview:lab];
        
        CustomButton * btn =[[CustomButton alloc]initWithFrame:CGRectMake(CGRectGetMaxX(lab.frame), 15.5, 6, 10) andImageName:@"Rectangle" andTitle:@"" andColor:[UIColor whiteColor] andFont:15];
        [leftView addSubview:btn];
        _phoneNumberTF.leftViewMode = UITextFieldViewModeAlways;
    }
    return _phoneNumberTF;
}

-(UITextField *)checkTF{
    if (!_checkTF) {
        _checkTF=[[UITextField alloc]initWithFrame:CGRectMake(52.5, CGRectGetMaxY(self.phoneNumberTF.frame)+30, KscreenWidth-101, 43)];
        _checkTF.borderStyle= UITextBorderStyleNone;
        _checkTF.layer.cornerRadius = 20;
        _checkTF.layer.borderWidth = .5;
        _checkTF.layer.backgroundColor = UIColorFromRGB(0xCFCFCF).CGColor;
        _checkTF.layer.masksToBounds = YES;
        _checkTF.backgroundColor=[UIColorFromRGB(0xFFFFFF)colorWithAlphaComponent:.21];
        _checkTF.attributedPlaceholder = [[NSAttributedString alloc]initWithString:@"请输入验证码" attributes:@{NSFontAttributeName:[UIFont boldSystemFontOfSize:12], NSForegroundColorAttributeName:UIColorFromRGB(0xFFFFFF)}];
        _checkTF.textColor=UIColorFromRGB(0xFFFFFF);
        _checkTF.font=[UIFont systemFontOfSize:12];
        _checkTF.keyboardType=UIKeyboardTypeDecimalPad;
        _checkTF.textAlignment = NSTextAlignmentCenter;
        UIView * rightView=[[UIView alloc]initWithFrame:CGRectMake(0, 0, 107, 43)];
        UIView * lineView=[[UIView alloc]initWithFrame:CGRectMake(0, 12, 1, 19.5)];
        lineView.backgroundColor=UIColorFromRGB(0xE2E4E4);
        [rightView addSubview:lineView];
        
        CustomButton * checkBtn =[[CustomButton alloc]initWithFrame:CGRectMake(CGRectGetMaxX(lineView.frame), 0, 90, 43) andTitle:@"获取验证码" andColor:UIColorFromRGB(0xFFFFFF) andFont:13];
        checkBtn.tag = 100;
        [rightView addSubview:checkBtn];
        [checkBtn addTarget:self action:@selector(getCheckCode:) forControlEvents:UIControlEventTouchUpInside];
        _checkTF.rightView = rightView;
        _checkTF.rightViewMode =UITextFieldViewModeAlways;
    }
    return _checkTF;
}
-(UITextView *)titleTextView{
    if (!_titleTextView) {
        _titleTextView=[[UITextView alloc]initWithFrame:CGRectMake(CGRectGetMaxX(self.selectBtn.frame)+6.5, CGRectGetMaxY(self.checkTF.frame)+16, CGRectGetWidth(self.phoneNumberTF.frame)-45, 60)];
        _titleTextView.textColor=[UIColor whiteColor];
        _titleTextView.backgroundColor=[UIColor clearColor];
        NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:@"登录即同《现在电影APP用户协议》和《现在电影APP隐私政策》"];
        [attributedString addAttribute:NSLinkAttributeName
                                 value:@"zhifubao://"
                                 range:[[attributedString string] rangeOfString:@"《现在电影APP用户协议》"]];
        [attributedString addAttribute:NSLinkAttributeName
                                 value:@"weixin://"
                                 range:[[attributedString string] rangeOfString:@"《现在电影APP隐私政策》"]];
        [attributedString addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:11] range:NSMakeRange(0, attributedString.length)];
        _titleTextView.attributedText = attributedString;
        _titleTextView.linkTextAttributes = @{NSForegroundColorAttributeName: [UIColor whiteColor],
                                         NSUnderlineColorAttributeName: [UIColor lightGrayColor],
                                         NSUnderlineStyleAttributeName: @(NSUnderlinePatternSolid)};
        
        _titleTextView.delegate = self;
        _titleTextView.editable = NO;        //必须禁止输入，否则点击将弹出输入键盘
        _titleTextView.scrollEnabled = NO;
        
    }
    return _titleTextView;
}
- (BOOL)textView:(UITextView *)textView shouldInteractWithURL:(NSURL *)URL inRange:(NSRange)characterRange {
    if ([[URL scheme] isEqualToString:@"zhifubao"]) {
        NSLog(@"支付宝支付---------------");
        [self.viewModel.qqSubject sendNext:nil];
        return NO;
    } else if ([[URL scheme] isEqualToString:@"weixin"]) {
        NSLog(@"微信支付---------------");
        [self.viewModel.wbSubject sendNext:nil];
        return NO;
    }
 
    return YES;
}
-(CustomButton *)selectBtn{
    if (!_selectBtn) {
        _selectBtn=[[CustomButton alloc]initWithFrame:CGRectMake(71, CGRectGetMaxY(self.checkTF.frame)+25, 12, 12) andImageName:@"select_login" andTitle:@"" andColor:[UIColor whiteColor] andFont:15];
        
    }
    return _selectBtn;
}
-(CustomLabel *)intructionLabel{
    if (!_intructionLabel) {
        NSString * str = @"登录即同《现在电影APP用户协议》和《现在电影APP隐私政策》";
        NSString * str1 = @"《现在电影APP用户协议》";
        NSString * str2 = @"《现在电影APP隐私政策》";
        _intructionLabel=[[CustomLabel alloc]initWithFrame:CGRectMake(CGRectGetMaxX(self.selectBtn.frame)+6.5, CGRectGetMaxY(self.checkTF.frame)+16, 220, 30) andText:str andFont:11 andColor:UIColorFromRGB(0X333333)];
        NSMutableAttributedString *attrStr = [[NSMutableAttributedString alloc] initWithString:str];
        
        NSRange range1 = [str rangeOfString:str1];
        NSRange range2 = [str rangeOfString:str2];
        [attrStr setAttributes:@{NSUnderlineStyleAttributeName : @(NSUnderlineStyleSingle)}
                         range:range1];
        [attrStr setAttributes:@{NSUnderlineStyleAttributeName : @(NSUnderlineStyleSingle)}
                         range:range2];
        _intructionLabel.attributedText = attrStr;
        _intructionLabel.numberOfLines = 2;
    }
    return _intructionLabel;
}
-(CustomButton *)loginBtn{
    if (!_loginBtn) {
        _loginBtn=[[CustomButton alloc]initWithFrame:CGRectMake(81.5, CGRectGetMaxY(self.intructionLabel.frame)+24, KscreenWidth-163, 45)  andTitle:@"登录" andColor:UIColorFromRGB(0xA0A0A0) andFont:18];
        _loginBtn.backgroundColor=UIColorFromRGB(0xEBEBEB);
        _loginBtn.layer.cornerRadius=24;
        _loginBtn.layer.masksToBounds = YES;
        
        [_loginBtn addTarget:self action:@selector(loginClick) forControlEvents:UIControlEventTouchUpInside];
    }
    return _loginBtn;
    
}
-(ThirdLoginShareView *)thirdView{
    if (!_thirdView) {
        _thirdView=[[ThirdLoginShareView alloc]initWithFrame:CGRectMake(0, KscreenHeight-130, KscreenWidth, 90) andInfoArray:@[@{@"title":@"qq",@"image":@"qq"},@{@"title":@"微博",@"image":@"微博"},@{@"title":@"微信",@"image":@"微信"}] andType:@"登陆"];
        _thirdView.delegate = self;
    }
    return _thirdView;
}


@end
